package com;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

public class MainAtomicVolatileTest {
	static ExecutorService epool = Executors.newFixedThreadPool(500);
	static MyData my = new MyData();
	
	public static void main(String[] args) {
		for(int i=0;i<1000;i++){
			final int a = i;
			epool.execute(new Runnable() {
				@Override
				public void run() {
					try {
						//if(a%2==0){
							my.add();
						//}else{
						//	my.sub();
						//}
							my.out();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			});
			epool.execute(new Runnable() {
				@Override
				public void run() {
					try {
						//if(a%2==0){
							//my.add();
						//}else{
							my.sub();
						//}
							my.out();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			});
		}
		try {
			Thread.sleep(10000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		my.out();
		epool.shutdown();
	}
}
class MyData{
	//volatile 
	AtomicInteger  i = new AtomicInteger(0),j= new AtomicInteger(0);
	int a,b;
	public void add() throws Exception{
		//Thread.sleep(3);
		a++;
		Thread.sleep(3);
		b++;
		i.getAndAdd(2);
		Thread.sleep(3);
		j.getAndAdd(2);
		
		//Thread.sleep(3);
	}
	public void sub() throws Exception{
		a--;
		Thread.sleep(3);
		b--;
		i.decrementAndGet();
		Thread.sleep(3);
		j.decrementAndGet();
		//Thread.sleep(3);
	}
	public void out(){
		if(i.intValue()<j.intValue()){
			System.out.println("i<j");
		}
		System.out.println("i="+i+",j="+j+";a="+a+",b="+b);
	}
}
